package com.szh.mysobproject.paging.source

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.szh.mysobproject.execption.ServiceException
import com.szh.mysobproject.http.ServiceCreator
import com.szh.mysobproject.model.UserFollow
import com.szh.mysobproject.other.FollowState
import com.szh.mysobproject.viewmodel.app.FansNetwork
import com.szh.mysobproject.viewmodel.app.FollowNetwork
import timber.log.Timber

class UserFollowOrFansPagingSource(
    private val userId: String,
    private val followState: FollowState
) :
    PagingSource<Int, UserFollow.UserFollowItem>() {
    override fun getRefreshKey(state: PagingState<Int, UserFollow.UserFollowItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, UserFollow.UserFollowItem> {
        return try {
            val page = params.key ?: FIRST_PAGE
            Timber.d("load ====>  userId is $userId  page is $page")
            val response = when (followState) {
                FollowState.FOLLOW -> FollowNetwork.loadUserFollowList(userId = userId, page = page)
                FollowState.FANS -> FansNetwork.loadUserFansList(userId = userId, page = page)
            }
            val responseData = response.getData()
            val prevKey = if (responseData.hasPre) page - 1 else null
            val nextKey = if (responseData.hasNext) page + 1 else null
            if (response.isSuccess()) LoadResult.Page(
                data = responseData.list,
                prevKey = prevKey,
                nextKey = nextKey
            ) else LoadResult.Error(ServiceException())
        } catch (t: Throwable) {
            t.printStackTrace()
            LoadResult.Error(t)
        }

    }

    companion object {
        private const val FIRST_PAGE = 1
    }
}